package com.ruoyi.pms.service.imp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.pms.domain.ProjectTask;
import com.ruoyi.pms.domain.vo.TaskDeferVO;
import com.ruoyi.pms.mapper.TaskMapper;
import com.ruoyi.pms.service.DynamicsService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.pms.mapper.TaskDeferMapper;
import com.ruoyi.pms.domain.TaskDefer;
import com.ruoyi.pms.service.ITaskDeferService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 任务延期Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-09
 */
@Service
public class TaskDeferServiceImpl implements ITaskDeferService
{
    @Autowired
    private TaskDeferMapper taskDeferMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    DynamicsService dynamicsService;
    @Autowired
    SysUserMapper sysUserMapper;

    /**
     * 查询任务延期
     * 
     * @param id 任务延期主键
     * @return 任务延期
     */
    @Override
    public TaskDefer selectPmsProjectTaskDeferById(String id)
    {
        return taskDeferMapper.selectPmsProjectTaskDeferById(id);
    }

    /**
     * 查询任务延期列表
     * 
     * @param taskDefer 任务延期
     * @return 任务延期
     */
    @Override
    public List<TaskDefer> selectPmsProjectTaskDeferList(TaskDefer taskDefer)
    {
        List<TaskDefer> list = taskDeferMapper.selectPmsProjectTaskDeferList(taskDefer);
        for(TaskDefer defer : list) {
            defer.setIsNew(false);
        }

        return list;
    }

    /**
     * 新增任务延期
     * 
     * @param taskDefer 任务延期
     * @return 结果
     */
    @Override
    @Transactional
    public int insertPmsProjectTaskDefer(TaskDefer taskDefer)
    {
        taskDefer.setCreateTime(DateUtils.getNowDate());
        ProjectTask task = taskMapper.selectById(taskDefer.getTaskId());
        taskDefer.setLastEndDate(task.getEndDate());
        taskDefer.setId(UUID.randomUUID().toString());
        taskDefer.setProjectId(task.getProjectId());
        taskDefer.setUpdateTime(DateUtils.getNowDate());
        taskDefer.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        taskDefer.setStatus(0);
        taskDeferMapper.insertPmsProjectTaskDefer(taskDefer);
        // 修改任务结束时间
//        task.setEndDate(taskDefer.getEndDate());
//        taskMapper.updateById(task);

        task.setEndDate(taskDefer.getEndDate());
//        dynamicsService.save(task.getProjectId(), "延长了任务[" + task.getTaskName()+"]截止日期到"
//                +DateUtils.parseDateToStr("yyyy-MM-dd", taskDefer.getEndDate()));
        return 1;
    }

    /**
     * 修改任务延期
     * 
     * @param taskDefer 任务延期
     * @return 结果
     */
    @Override
    public int updatePmsProjectTaskDefer(TaskDefer taskDefer)
    {
        taskDefer.setUpdateTime(DateUtils.getNowDate());
        return taskDeferMapper.updatePmsProjectTaskDefer(taskDefer);
    }

    /**
     * 批量删除任务延期
     * 
     * @param ids 需要删除的任务延期主键
     * @return 结果
     */
    @Override
    public int deletePmsProjectTaskDeferByIds(String[] ids)
    {
        return taskDeferMapper.deletePmsProjectTaskDeferByIds(ids);
    }

    /**
     * 删除任务延期信息
     * 
     * @param id 任务延期主键
     * @return 结果
     */
    @Override
    public int deletePmsProjectTaskDeferById(String id)
    {
//        TaskDefer taskDefer = taskDeferMapper.selectPmsProjectTaskDeferById(id);
//        ProjectTask task = taskMapper.selectById(taskDefer.getTaskId());
//        task.setEndDate(taskDefer.getLastEndDate());
//        taskMapper.updateById(task);
//        dynamicsService.save(task.getProjectId(), "删除了[" + task.getTaskName()+"]的延长时间，截止日期变更为"
//                +DateUtils.parseDateToStr("yyyy-MM-dd", task.getEndDate()));
        return taskDeferMapper.deletePmsProjectTaskDeferById(id);
    }

    @Override
    public List<TaskDeferVO> selectAuditDeferList(TaskDefer taskDefer) {
        List<TaskDeferVO> listVO = new ArrayList<>();
        List<TaskDefer> list = taskDeferMapper.selectPmsProjectTaskDeferList(taskDefer);
        if(list.size() == 0) {
            return new ArrayList<>();
        }
        List<String> taskIds = list.stream().map(TaskDefer::getTaskId).collect(Collectors.toList());
        List<ProjectTask> taskList = taskMapper.selectList(new QueryWrapper<ProjectTask>().in("id", taskIds));
        List<Long> userIds = taskList.stream().map(ProjectTask::getAssignUserId).collect(Collectors.toList());
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().in("user_id", userIds));

        Map<String, ProjectTask> taskMap = taskList.stream().collect(Collectors.toMap(ProjectTask::getId, t -> t));
        Map<Long, SysUser> userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId, u -> u));

        list.forEach(defer -> {
            TaskDeferVO vo = new TaskDeferVO();
            BeanUtils.copyProperties(defer, vo);
            vo.setTaskName(taskMap.get(defer.getTaskId()).getTaskName());
            vo.setNickName(userMap.get(taskMap.get(defer.getTaskId()).getAssignUserId()).getNickName());
            listVO.add(vo);
        });
        return listVO;
    }

    @Override
    @Transactional
    public void auditDefer(TaskDefer taskDefer) {
        if(StringUtils.isEmpty(taskDefer.getId()) || taskDefer.getStatus() == null) {
            return;
        }
        TaskDefer updateDefer = new TaskDefer();
        updateDefer.setId(taskDefer.getId());
        updateDefer.setStatus(taskDefer.getStatus());
        taskDeferMapper.updatePmsProjectTaskDefer(updateDefer);

        TaskDefer taskDeferDB = taskDeferMapper.selectPmsProjectTaskDeferById(taskDefer.getId());
        ProjectTask task = taskMapper.selectById(taskDeferDB.getTaskId());
        // 修改任务结束时间
        if(taskDefer.getStatus() == 1) {
            task.setEndDate(taskDeferDB.getEndDate());
            taskMapper.updateById(task);
            dynamicsService.save(task.getProjectId(), "审核通过了延长了任务[" + task.getTaskName()+"]的申请，截止日期到"
                    +DateUtils.parseDateToStr("yyyy-MM-dd", taskDeferDB.getEndDate()));
        }
    }
}
